package com.eqxiu.ieditor.api.controller.mall;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.google.gson.Gson;
import eqxiu.mall.product.dto.BannerConfigDTO;
import eqxiu.mall.product.service.api.BannerConfigServiceApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = {"/api/wap/banner"})
public class BannerController {
    private final Logger LOGGER = LoggerFactory.getLogger(BannerController.class);
    @Autowired
    private BannerConfigServiceApi bannerConfigServiceApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${wap.index.banner.id}")
    private Integer wapIndexBannerId;

    @Value("${wap.h5.banner.id}")
    private Integer wapH5BannerId;

    @Value("${wap.longpage.banner.id}")
    private Integer wapLongPageBannerId;

    @Value("${wap.form.banner.id}")
    private Integer wapFormBannerId;

    @Value("${wap.gc.banner.id}")
    private Integer wapGcBannerId;

    @Value("${wap.design.banner.id}")
    private Integer wapDesignBannerId;
    @Value("${wap.video.banner.id}")
    private Integer wapVideoBannerId;


    //首页和各子商城8个配置banner
    @Value("${wap.index.config.banner.id}")
    private Integer wapIndexConfigBannerId;

    @Value("${wap.h5.config.banner.id}")
    private Integer wapH5ConfigBannerId;

    @Value("${wap.longpage.config.banner.id}")
    private Integer wapLongPageConfigBannerId;

    @Value("${wap.form.config.banner.id}")
    private Integer wapFormConfigBannerId;

    @Value("${wap.gc.config.banner.id}")
    private Integer wapGcConfigBannerId;
    @Value("${wap.design.config.banner.id}")
    private Integer wapDesignConfigBannerId;
    @Value("${wap.video.config.banner.id}")
    private Integer wapVideoConfigBannerId;

    //广告位banner
    @Value("${wap.index.adv.banner.id}")
    private Integer wapIndexAdvBannerId;

    @Value("${wap.index.adv.banner.up.id}")
    private Integer wapIndexAdvBannerUpId;

    @Value("${wap.h5.adv.banner.id}")
    private Integer wapH5AdvBannerId;

    @Value("${wap.longpage.adv.banner.id}")
    private Integer wapLongPageAdvBannerId;

    @Value("${wap.form.adv.banner.id}")
    private Integer wapFormAdvBannerId;

    @Value("${wap.gc.adv.banner.id}")
    private Integer wapGcAdvBannerId;

    @Value("${wap.design.adv.banner.id}")
    private Integer wapDesignAdvBannerId;

    @Value("${wap.video.adv.banner.id}")
    private Integer wapVideoAdvBannerId;



    //底部banner
    @Value("${wap.index.bottom.banner.id}")
    private Integer wapIndexBottomBannerId;

    @Value("${wap.h5.bottom.banner.id}")
    private Integer wapH5BottomBannerId;

    @Value("${wap.longpage.bottom.banner.id}")
    private Integer wapLongPageBottomBannerId;

    @Value("${wap.form.bottom.banner.id}")
    private Integer wapFormBottomBannerId;

    @Value("${wap.gc.bottom.banner.id}")
    private Integer wapGcBottomBannerId;

    /**
     * reids缓存时间
     **/
    @Value("${redis.timeOut}")
    private Integer redisTimeOut;

    /**
     * 轮播图
     * @param type
     * @return
     */
    @PostMapping("/broadcast")
    @ResponseBody
    public ResultData bannerBroadcastList(Integer type) {
        LOGGER.info("type接口返回==" + new Gson().toJson(type));
        List<BannerConfigDTO> bannerCarouselConfigs = new ArrayList<>();
        //type 0-wap商城首页，1-h5，2-长页，3-易表单，4-互动,5-轻设计，6-视频
        Integer bannerId = wapIndexBannerId;
        if(null == type){
            type = 0;
        }
        if( 0==type){
            bannerId = wapIndexBannerId;
        }else if(1==type){
            bannerId= wapH5BannerId;
        }else if(2==type){
            bannerId= wapLongPageBannerId;
        }else if(3==type){
            bannerId= wapFormBannerId;
        }else if(4==type){
            bannerId = wapGcBannerId;
        }else if(5==type){
            bannerId =wapDesignBannerId;
        }else if(6==type){
            bannerId =wapVideoBannerId;
        }
        String cachedKey = "wapBannerBroadcastList:" + type;
        if (redisTemplate.opsForValue().size(cachedKey) == null || redisTemplate.opsForValue().size(cachedKey) == 0) {
            try {
                // 判断获取的banner配置的个数
                bannerCarouselConfigs = bannerConfigServiceApi.findBannerConfigByBannerId(bannerId);
                if (!CollectionUtils.isEmpty(bannerCarouselConfigs)) {
                    if(bannerCarouselConfigs.size()>5){
                        bannerCarouselConfigs = bannerCarouselConfigs.subList(0,5);
                    }
                    redisTemplate.opsForValue().set(cachedKey, JSONObject.toJSONString(bannerCarouselConfigs), redisTimeOut, TimeUnit.MINUTES);
                }
                LOGGER.info("broadcast接口返回==未用缓存==" + new Gson().toJson(bannerCarouselConfigs));
                return ResultData.result(true).setList(bannerCarouselConfigs);
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
                return ResultData.result(true).setList(bannerCarouselConfigs);
            }
        } else {
            String s = redisTemplate.opsForValue().get(cachedKey);
            bannerCarouselConfigs = (List<BannerConfigDTO>) JSONArray.parseArray(s, BannerConfigDTO.class);
            LOGGER.info("broadcast接口返回==缓存==" + new Gson().toJson(bannerCarouselConfigs));
            return ResultData.result(true).setList(bannerCarouselConfigs);
        }
    }


    @PostMapping("/tenConfigBanner")
    @ResponseBody
    public ResultData bannerConfigList(Integer type) {
        LOGGER.info("type接口返回==" + new Gson().toJson(type));
        List<BannerConfigDTO> bannerConfigs = new ArrayList<>();
        //type 0-wap商城首页，1-h5，2-长页，3-易表单，4-互动,5-请设计，6-视频
        Integer bannerConfigId = wapIndexConfigBannerId;
        if(null == type){
            type = 0;
        }
        if( 0==type){
            bannerConfigId = wapIndexConfigBannerId;
        }else if(1==type){
            bannerConfigId = wapH5ConfigBannerId;
        }else if(2==type){
            bannerConfigId = wapLongPageConfigBannerId;
        }else if(3==type){
            bannerConfigId = wapFormConfigBannerId;
        }else if(4==type){
            bannerConfigId = wapGcConfigBannerId;
        }else if(5==type){
            bannerConfigId = wapDesignConfigBannerId;
        }else if(6==type){
            bannerConfigId = wapVideoConfigBannerId;
        }
        String cachedKey = "wapBannerConfigList:" + type;
        if (redisTemplate.opsForValue().size(cachedKey) == null || redisTemplate.opsForValue().size(cachedKey) == 0) {
            try {
                // 判断获取的banner配置的个数
                bannerConfigs = bannerConfigServiceApi.findBannerConfigByBannerId(bannerConfigId);
                if (!CollectionUtils.isEmpty(bannerConfigs)) {
                    redisTemplate.opsForValue().set(cachedKey, JSONObject.toJSONString(bannerConfigs), redisTimeOut, TimeUnit.MINUTES);
                }
                LOGGER.info("tenConfigBanner接口返回==未用缓存==" + new Gson().toJson(bannerConfigs));
                return ResultData.result(true).setList(bannerConfigs);
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
                return ResultData.result(true).setList(bannerConfigs);
            }
        } else {
            String s = redisTemplate.opsForValue().get(cachedKey);
            bannerConfigs = (List<BannerConfigDTO>) JSONArray.parseArray(s, BannerConfigDTO.class);
            LOGGER.info("tenConfigBanner接口返回==缓存==" + new Gson().toJson(bannerConfigs));
            return ResultData.result(true).setList(bannerConfigs);
        }
    }



    @PostMapping("/advAndBottomBanner")
    @ResponseBody
    public ResultData advAndBottomBanner(Integer type) {
        LOGGER.info("type接口返回==" + new Gson().toJson(type));
        Map map = new HashMap();
        //type 0-wap商城首页，1-h5，2-长页，3-易表单，4-互动
        Integer bannerConfigId = wapIndexBottomBannerId;
        Integer bannerAdvId = wapIndexAdvBannerId;
        if(null == type){
            type = 0;
        }
        if( 0==type){
            bannerConfigId = wapIndexBottomBannerId;
            bannerAdvId = wapIndexAdvBannerId;
        }else if(1==type){
            bannerConfigId = wapH5BottomBannerId;
            bannerAdvId = wapH5AdvBannerId;
        }else if(2==type){
            bannerConfigId = wapLongPageBottomBannerId;
            bannerAdvId = wapLongPageAdvBannerId;
        }else if(3==type){
            bannerConfigId = wapFormBottomBannerId;
            bannerAdvId = wapFormAdvBannerId;
        }else if(4==type){
            bannerConfigId = wapGcBottomBannerId;
            bannerAdvId = wapGcAdvBannerId;
        }else if(5==type){
            bannerAdvId = wapDesignAdvBannerId;
        }else if(6==type){
            bannerAdvId = wapVideoAdvBannerId;
        }
        String cachedKey = "wapAdvAndBottomBannerLists:" + type;
       // if (redisTemplate.opsForValue().size(cachedKey) == null || redisTemplate.opsForValue().size(cachedKey) == 0) {
            try {
                // 判断获取的banner配置的个数
                List<BannerConfigDTO> bannerAdvs = bannerConfigServiceApi.findBannerConfigByBannerId(bannerAdvId);
                map.put("bannerUpAdvs",bannerAdvs);
                if(!CollectionUtils.isEmpty(bannerAdvs) && bannerAdvs.size()>1){
                    List<BannerConfigDTO> bannerAdvsList = bannerAdvs.subList(0,1);
                    map.put("bannerUpAdvs",bannerAdvsList);
                }
                LOGGER.info("map接口返回==缓存==" + new Gson().toJson(map));
                //目前只有综合首页有底部banner
                if(0==type){
                    List<BannerConfigDTO> bannerConfigs = bannerConfigServiceApi.findBannerConfigByBannerId(bannerConfigId);
                    List<BannerConfigDTO> bannerConfigDown = bannerConfigServiceApi.findBannerConfigByBannerId(bannerAdvId);
                    map.put("bannerAdvs",bannerConfigDown);//精选模板下banner
                    List<BannerConfigDTO> bannerUpAdvs = bannerConfigServiceApi.findBannerConfigByBannerId(wapIndexAdvBannerUpId);
                    map.put("bannerUpAdvs",bannerUpAdvs);//精选模板上banner
                    if(!CollectionUtils.isEmpty(bannerUpAdvs) && bannerUpAdvs.size()>1){
                        List<BannerConfigDTO> bannerAdvsUpList = bannerUpAdvs.subList(0,1);
                        map.put("bannerUpAdvs",bannerAdvsUpList);
                    }
                    map.put("bannerBottoms",bannerConfigs);
                }else{
                    map.put("bannerBottoms","");
                    map.put("bannerAdvs","");
                    LOGGER.info("map接口返回==缓存==" + new Gson().toJson(map));
                }
              /*  if (map != null) {
                    redisTemplate.opsForValue().set(cachedKey, JSONObject.toJSONString(map), 1, TimeUnit.MINUTES);
                }*/
                LOGGER.info("advAndBottomBanner接口返回==未用缓存==" + new Gson().toJson(map));
                return ResultData.result(true).setMap(map);
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
                return ResultData.result(true).setMap(map);
            }
       /* } else {
            String s = redisTemplate.opsForValue().get(cachedKey);
            map = JSON.parseObject(s);
            LOGGER.info("advAndBottomBanner接口返回==缓存==" + new Gson().toJson(map));
            return ResultData.result(true).setMap(map);
        }*/
    }

}
